package library.system.manager;

import library.system.entity.Book;
import library.system.entity.Reader;
import library.system.entity.BorrowRecord;
import library.system.exception.BookNotFoundException;
import library.system.exception.ReaderNotFoundException;
import library.system.exception.StockInsufficientException;
import library.system.exception.BorrowLimitException;

import java.io.*;
import java.util.*;

public class LibraryManager {
    private Map<String, Book> books = new HashMap<>();
    private Map<String, Reader> readers = new HashMap<>();
    private List<BorrowRecord> records = new ArrayList<>();
    private static final int BORROW_LIMIT = 5;  // 读者最大借书总数限制
    private static final String DATA_FILE = "library.data";

    // 加载本地数据（不变）
    public void loadData() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(DATA_FILE))) {
            books = (Map<String, Book>) ois.readObject();
            readers = (Map<String, Reader>) ois.readObject();
            records = (List<BorrowRecord>) ois.readObject();
            System.out.println("数据加载成功");
        } catch (FileNotFoundException e) {
            System.out.println("首次运行，无历史数据");
        } catch (Exception e) {
            System.out.println("数据加载失败：" + e.getMessage());
        }
    }

    // 保存数据到本地（不变）
    public void saveData() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(DATA_FILE))) {
            oos.writeObject(books);
            oos.writeObject(readers);
            oos.writeObject(records);
            System.out.println("数据保存成功");
        } catch (Exception e) {
            System.out.println("数据保存失败：" + e.getMessage());
        }
    }

    // 添加图书（不变）
    public void addBook(Book book) {
        books.put(book.getIsbn(), book);
    }

    // 添加读者（不变）
    public void addReader(Reader reader) {
        readers.put(reader.getId(), reader);
    }

    // 删除指定读者（不变）
    public void deleteReader(String readerId) throws ReaderNotFoundException {
        if (!readers.containsKey(readerId)) {
            throw new ReaderNotFoundException("读者不存在，无法删除");
        }
        readers.remove(readerId);
        System.out.println("读者删除成功");
    }

    // 查看所有图书（不变）
    public void showAllBooks() {
        if (books.isEmpty()) {
            System.out.println("暂无图书信息");
            return;
        }
        System.out.println("\n===== 图书列表 =====");
        System.out.println("ISBN\t\t书名\t\t作者\t\t出版社\t\t库存");
        System.out.println("-----------------------------------------------------");
        for (Book book : books.values()) {
            System.out.printf("%s\t%s\t%s\t%s\t%d\n",
                    book.getIsbn(), book.getName(), book.getAuthor(), book.getPress(), book.getStock());
        }
    }

    // 查看所有借阅记录（不变）
    public void showAllRecords() {
        if (records.isEmpty()) {
            System.out.println("暂无借阅记录");
            return;
        }
        System.out.println("\n===== 借阅记录 =====");
        System.out.println("ISBN\t\t读者ID\t\t借书时间\t\t\t还书时间");
        System.out.println("-----------------------------------------------------");
        for (BorrowRecord r : records) {
            String returnTime = (r.getReturnTime() == null) ? "未还书" : r.getReturnTime().toString();
            System.out.printf("%s\t%s\t%s\t%s\n",
                    r.getIsbn(), r.getReaderId(), r.getBorrowTime().toString(), returnTime);
        }
    }

    // 【修改核心】借书操作（支持选择借阅数量）
    public void borrowBook(String isbn, String readerId, int borrowNum) throws Exception {
        Book book = books.get(isbn);
        Reader reader = readers.get(readerId);

        // 基础校验
        if (book == null) throw new BookNotFoundException("图书不存在");
        if (reader == null) throw new ReaderNotFoundException("读者不存在");
        if (borrowNum <= 0) throw new Exception("借阅数量必须大于0");

        // 库存超量校验
        if (borrowNum > book.getStock()) {
            throw new StockInsufficientException("借阅数量超量（当前库存：" + book.getStock() + "本）");
        }

        // 读者借书总数超限校验
        if (reader.getBorrowCount() + borrowNum > BORROW_LIMIT) {
            throw new BorrowLimitException("超过最大借书数量（可借：" + (BORROW_LIMIT - reader.getBorrowCount()) + "本）");
        }

        // 更新库存和读者借书数量
        book.setStock(book.getStock() - borrowNum);
        reader.setBorrowCount(reader.getBorrowCount() + borrowNum);

        // 生成对应数量的借阅记录（每本1条）
        for (int i = 0; i < borrowNum; i++) {
            records.add(new BorrowRecord(isbn, readerId));
        }

        System.out.println("借书成功，共借阅 " + borrowNum + " 本");
    }

    // 还书操作（不变）
    public void returnBook(String isbn, String readerId) throws Exception {
        Book book = books.get(isbn);
        Reader reader = readers.get(readerId);

        if (book == null) throw new BookNotFoundException("图书不存在");
        if (reader == null) throw new ReaderNotFoundException("读者不存在");

        // 校验是否有未还记录
        boolean hasUnreturned = records.stream().anyMatch(
                r -> r.getIsbn().equals(isbn) && r.getReaderId().equals(readerId) && r.getReturnTime() == null
        );
        if (!hasUnreturned) throw new Exception("该读者未借阅此图书，无法还书");

        // 恢复库存和借书数量
        book.setStock(book.getStock() + 1);
        reader.setBorrowCount(reader.getBorrowCount() - 1);

        // 更新还书时间
        for (BorrowRecord r : records) {
            if (r.getIsbn().equals(isbn) && r.getReaderId().equals(readerId) && r.getReturnTime() == null) {
                r.setReturnTime(new Date());
                break;
            }
        }
        System.out.println("还书成功");
    }
}   